    <?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class myOrder{
    const NEW_ORDER_STATUS = 1;
    const NEW_ORDER_NONE_DISCOUNT = NULL;
    
    private $user;
    private $deliveryData;
    private $deliveryType;
    private $orderId;
    
    private function loadProducts(){
        foreach(myBucket::getInstance()->getObjects() as $object){
            $ordProd = new OrderProducts();
            $ordProd->setProductId($object['pid']);
            $ordProd->setOrdersId($this->orderId);
            $ordProd->setCount($object['nmb']);
            $ordProd->save();
        }
    }
    
    private function load(){
        $deliveryData = DeliveryDataTable::getInstance()->findOneBy('user_id', $this->user->getId());
        if($deliveryData){
            $this->deliveryData = $deliveryData->getId();
        }
        else{
            throw new Exception('Nie znaleziono adresu do dostarczenia.');
        }
        $deliveryType = DeliveryTypeTable::getInstance()->findOneBy('id', $this->deliveryType);
        if(!$deliveryType){
            throw new Exception('Nie znaleziono podanego typu transportu. Spróbj ponownie później.');
        }
    }
    
    private function create(){
        if(myBucket::getInstance()->count()){
            $order = new Orders();
            $order->setDeliveryDataId($this->deliveryData);
            $order->setDeliveryTypeId($this->deliveryType);
            $order->setOrderStatusId(self::NEW_ORDER_STATUS);
            $order->setOrderDiscountId(self::NEW_ORDER_NONE_DISCOUNT);
            $order->save();
            $this->orderId = $order->getId();
        }
        else{
            throw new Exception('Nie można potwierdzić zamówienia bez produktów.');
        }
    }
    
    public function __construct($user, $deliveryType) {
        $this->user = $user;
        $this->deliveryType = $deliveryType;
        $this->load();
        $this->create();
        $this->loadProducts();
    }
    
    public function clean(){
        unset($this->user);
        unset($this->deliveryData);
        unset($this->deliveryType);
        myBucket::getInstance()->clean();
    }
}